const { Car, Dictionary, CarModel } = require('../models');
const sequelize = require('sequelize');
const { Op } = sequelize;
const dayjs = require('dayjs');

class CarService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter = [], page = 1, page_size = 20) {
		const { name, category_id, city_code } = filter;
		const where = {};
		if (name) where['name'] = { [Op.like]: `%${name}%` };
		if (category_id) where['category_id'] = category_id;

		if (city_code) {
			where[Op.or] = [
				sequelize.where(sequelize.fn('json_keys', sequelize.col('Car._region')), {
					[Op.regexp]: `(${[city_code].join('|')})`
				}),
				//不设置地区则面向全国
				sequelize.where(sequelize.fn('ifnull', sequelize.col('Car._region'), ''), '')
			];
		}

		const { count: total, rows: data } = await Car.findAndCountAll({
			where,
			include: {
				model: Dictionary,
				as: 'category',
				attributes: ['name']
			},

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'asc']
			]
		});

		return {
			data: data.map((d) => {
				if (d.model_url) d.model_url += `${d.model_url.includes('?') ? '&' : '?'}id=${d.id}`;
				if (d.content_url) d.content_url += `${d.content_url.includes('?') ? '&' : '?'}id=${d.id}`;

				return d;
			}),
			total
		}
	}

	async info(where) {
		const car = await Car.findOne({
			where,
			include: [{
				/*
				model: CarModel,
				as: 'models'
				*/

				association: Car.Models
			}, {
				model: Dictionary,
				as: 'category',
				attributes: ['name', 'model']
			}]
		}).then((data) => {
			if (!data) return {};

			data = data.toJSON();

			//格式化新的配件信息
			const color = [];
			const option = [];

			data.models.forEach((d) => {
				if (d.group_id === 1) color.push(d);
				else if (d.group_id === 2) option.push(d);
			});

			data.models = {
				color,
				option
			}

			if (!data.params) data.params = [];

			return data;
		});

		return car;
	}

	async delete(id) {
		await Car.destroy({
			where: {
				id: { [Op.in]: String(id).split(',') }
			}
		});

		await CarModel.destroy({
			where: {
				car_id: { [Op.in]: String(id).split(',') }
			}
		})
		return true;
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		params.params = JSON.parse(params.params);
		const { id } = params;
		const models = JSON.parse(params.models);

		params.models = Object.keys(models).reduce((res, key) => {
			res = res.concat(models[key].map(d => {
				d.group_id = ['color', 'option'].findIndex(v => v === key) + 1;
				return d;
			}));
			return res;
		}, []);

		if (!params.supplier_id) params.supplier_id = null;

		if (params.region) params.region = JSON.parse(params.region);
		if (params._region) params._region = JSON.parse(params._region);

		if (id) {
			await Car.update(params, {
				where: {
					id
				}
			});
			const car = await Car.findByPk(id);

			const carModels = [];
			for (const d of params.models) {
				if (d.id) {
					await CarModel.update(d, {
						where: {
							id: d.id
						}
					});
					carModels.push(await CarModel.findByPk(d.id));
				} else {
					carModels.push(await CarModel.create(d));
					/*
					CarModel.build(d);
					CarModel.save();
					*/
				}
			};

			//直接删除全部（只是去掉app_car_model表中car_id的值，表记录依旧存在）

			//await car.removeModels(await car.getModels());
			//等效于：await car.setModels([]);

			//然后重新绑定
			//await car.addModels(carModels);


			//removeModels + addModels = setModels
			await car.setModels(carModels);

			return car;
		} else {
			/*
			const car = await Car.create(params);
			for (const d of params.models) {
				await car.createModel(d);
			}
			*/

			const car = await Car.create(params, {
				include: [
					{
						association: Car.Models,
						as: 'models'
					},
					/*
					{
						model: CarModel,
						as: 'models'
					}
					*/
				]
			})

			return car;
		}
	}
}

exports = module.exports = CarService;
